package com.sunwayworld.basemodule.samplemanage.sample.io;

import com.sunwayworld.basemodule.basedata.exporttemplate.service.LimsGenericTemplateService;
import com.sunwayworld.basemodule.basedata.sampletype.bean.LimsSampleTypeBean;
import com.sunwayworld.basemodule.basedata.sampletype.service.LimsSampleTypeService;
import com.sunwayworld.basemodule.business.ordertask.bean.LimsOrderTaskBean;
import com.sunwayworld.basemodule.business.ordertask.service.LimsOrderTaskService;
import com.sunwayworld.framework.io.excel.utils.ExcelUtils;
import com.sunwayworld.framework.mybatis.mapper.MapperParameter;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.utils.BeanUtils;
import com.sunwayworld.framework.utils.StringUtils;
import com.sunwayworld.module.sys.code.bean.CoreCodeBean;
import com.sunwayworld.module.sys.code.service.CoreCodeService;
import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.List;

/**
 * @ClassName LimsDeriSampleGenerateExportTemplate
 * @Author zhoujq
 * @Date 2023/3/15
 * @Version 1.0
 **/
@Component(value = "LimsDeriSampleGenerateExportTemplate")
@GikamBean
public class LimsDeriSampleGenerateExportTemplate implements LimsGenericTemplateService<String> {

    @Autowired
    @Lazy
    private LimsOrderTaskService limsOrderTaskService;

    @Autowired
    @Lazy
    private LimsSampleTypeService limsSampleTypeService;

    @Autowired
    @Lazy
    private CoreCodeService coreCodeService;

    @Override
    public void initTemplateData(Path path, String id) {
        if (StringUtils.isEmpty(id)) {
            return;
        }
        try {
            InputStream in = new FileInputStream(path.toString());
            Workbook workBook = WorkbookFactory.create(in);
            Sheet sheet = workBook.getSheetAt(0);

            MapperParameter mapperParameter = new MapperParameter();
            mapperParameter.setFilter(SearchFilter.instance().match("runId", id).filter(MatchPattern.EQ).match("status", "logged").filter(MatchPattern.SB).match("flag", "1").filter(MatchPattern.EQ));
//            mapperParameter.put("queries_raw", "1");
            List<LimsOrderTaskBean> orderTaskBeans = limsOrderTaskService.selectList(mapperParameter);
            if (!orderTaskBeans.isEmpty()) {
                //补充数据
                addInfo(sheet, workBook, orderTaskBeans);
            }
            in.close();
            FileOutputStream outputStream = new FileOutputStream(path.toString());
            workBook.write(outputStream);
            outputStream.close();
            workBook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void addInfo(Sheet sheet, Workbook wb, List<LimsOrderTaskBean> orderTaskBeans) {
        CellStyle leftCellStyle = ExcelUtils.getLeftCellStyle(wb);
        Row firstRow = sheet.getRow(1);
        int endCellNum = firstRow.getPhysicalNumberOfCells();
        //获取列信息：

        for (int i = 0; i < orderTaskBeans.size(); i++) {
            Row row = sheet.createRow(i + 2);
            for (int j = 1; j < endCellNum - 3; j++) {
                Cell cell = row.createCell(j);
                cell.setCellStyle(leftCellStyle);
                String value = BeanUtils.getPropertyValue(orderTaskBeans.get(i), firstRow.getCell(j).getCellComment().getString().getString()).toString();
                cell.setCellValue(value);
            }
            for (int j = endCellNum - 3; j < endCellNum; j++) {
                Cell cell = row.createCell(j);
                cell.setCellStyle(leftCellStyle);
                cell.setCellValue("");
            }
        }

        for (int j = 1; j < endCellNum; j++) {
            Cell cell = firstRow.getCell(j);
            cell.setCellStyle(leftCellStyle);
            String comment = cell.getCellComment().getString().getString();
            if ("derivativeSampleType".equalsIgnoreCase(comment)) {
                MapperParameter mapperParameter = new MapperParameter();
                mapperParameter.put("filter_derivativeType", "1");
                List<LimsSampleTypeBean> sampleTypeBeans = limsSampleTypeService.selectList(mapperParameter);
                addDataValidate(sheet, sampleTypeBeans.stream().map(LimsSampleTypeBean::getSampleTypeName).toArray(String[]::new), j);
            } else if ("generateDerivativeType".equalsIgnoreCase(comment)) {
                List<CoreCodeBean> deriTypes = coreCodeService.selectListByFilter(SearchFilter.instance().match("codeCategoryId", "derivativeMakeType").filter(MatchPattern.EQ));
                addDataValidate(sheet, deriTypes.stream().map(CoreCodeBean::getCodeName).toArray(String[]::new), j);
            }
        }
    }

    private void addDataValidate(Sheet sheet, String[] validateDatas, int col) {
        DataValidationHelper helper = sheet.getDataValidationHelper();
        DataValidationConstraint constraint = helper.createExplicitListConstraint(validateDatas);
        //参数顺序：开始行、结束行、开始列、结束列
        CellRangeAddressList regions = new CellRangeAddressList(2, 120, col, col);
        DataValidation validation = helper.createValidation(constraint,regions);
        validation.setSuppressDropDownArrow(true);
        validation.setShowErrorBox(true);
        sheet.addValidationData(validation);
    }
}

